using System;
using System.Collections.Generic;
using Castle.ActiveRecord;

namespace Scrummer.Models
{
	[ActiveRecord]
	public class Project : AbstractModel<Project>
	{
		private IList<Sprint> sprints;
		private string name;
		private Backlog backlog;

		public Project()
		{
			backlog = new Backlog();
		}

		[HasMany(Cascade=ManyRelationCascadeEnum.AllDeleteOrphan)]
		public IList<Sprint> Sprints
		{
			get
			{
				if (sprints == null)
					sprints = new List<Sprint>();

				return sprints;
			}
			protected set { sprints = value; }
		}

		[Property]
		public string Name
		{
			get { return name; }
			set { name = value; }
		}

		[BelongsTo]
		public Backlog Backlog
		{
			get { return backlog; }
			protected set { backlog = value; }
		}

		public void AddWorkItem(WorkItem workItem)
		{
			if (backlog == null)
				backlog = new Backlog();

			backlog.Add(workItem);
		}

		public void AddSprint(Sprint sprint)
		{
			if (sprint == null)
				throw new ArgumentNullException("Cannot add a null sprint");

			Sprints.Add(sprint);
		}

		protected override void OnSaving()
		{
			if (backlog != null && backlog.IsNew)
				backlog.Create();
			else if (backlog != null)
				backlog.Save();

			if (sprints != null)
				foreach (Sprint sprint in sprints)
					if (sprint.IsNew)
						sprint.Create();

			base.OnSave();
		}

		protected override void OnCreating()
		{
			if (backlog != null && backlog.IsNew)
				Backlog.Create();

			if (sprints != null)
				foreach (Sprint sprint in sprints)
					if (sprint.IsNew)
						sprint.Create();

			base.OnCreating();
		}
	}
}
